package HashTable;

import java.util.HashSet;
import java.util.Iterator;

/**
 * @ClassName Intersection
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-18 14:33
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class Intersection {


    /**
     * 349. 两个数组的交集
     * 给定两个数组 nums1 和 nums2 ，返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
     * <p>
     * 示例 1：
     * <p>
     * 输入：nums1 = [1,2,2,1], nums2 = [2,2]
     * 输出：[2]
     * 示例 2：
     * <p>
     * 输入：nums1 = [4,9,5], nums2 = [9,4,9,8,4]
     * 输出：[9,4]
     * 解释：[4,9] 也是可通过的
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection(int[] nums1, int[] nums2) {

        HashSet<Integer> hashSet = new HashSet<>();

        for (int num : nums1) {
            hashSet.add(num);
        }

        HashSet<Integer> resultSet = new HashSet<>();
        for (int i = 0; i < nums2.length; i++) {
            if (hashSet.contains(nums2[i])) {
                resultSet.add(nums2[i]);
            }
        }
        int size = resultSet.size();
        int[] resultArray = new int[size];
        int index = 0;
        Iterator<Integer> iterator = resultSet.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            resultArray[index++] = next;
        }
        return resultArray;
    }

    public static void main(String[] args) {
        Intersection intersection = new Intersection();
        int[] a = new int[]{1, 2, 2, 1};
        int[] b = new int[]{2, 2};


        int[] intersection1 = intersection.intersection(a, b);
        for (int i = 0; i < intersection1.length; i++) {
            System.out.println(intersection1[i]);
        }
    }
}